package cn.school.demo.ui.notice

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import cn.school.demo.MainViewModel
import cn.school.demo.MainViewModel.Companion.UPDATE_NOTICE
import cn.school.demo.pojo.Notice
import cn.school.demo.util.HttpsUtil
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.JsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.JsonObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup

private const val URL = "https://www.sdtbu.edu.cn/index/tzgg.htm"

class NoticeWorker(val context: Context, workerParams: WorkerParameters) :
    Worker(context, workerParams) {
    val noticesList: MutableList<Notice> = mutableListOf()
    private val mLocalBroadcastManager: LocalBroadcastManager =
        LocalBroadcastManager.getInstance(context)

    override fun doWork(): Result {
        return when (getNotice(URL)) {
            true -> {
                val intent = Intent(UPDATE_NOTICE)
                intent.putExtra("notice", GsonUtils.toJson(noticesList))
                mLocalBroadcastManager.sendBroadcast(intent)
                LogUtils.e("我发送广播了啊")
                Result.success()
            }
            else -> {
                Result.failure()
            }
        }
    }

    private fun getNotice(mainUrl: String): Boolean {
        HttpsUtil().trustEveryone()
        val document = Jsoup.connect(mainUrl)
            .userAgent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0").get()
        val urls = document.select("a.c75870").eachAttr("href")
        val title = document.select("a.c75870").eachText()
        val dates = document.select("p.c75870_date").eachText()
        if (NoticeViewModel().notice.size == 0 || NoticeViewModel().notice[0].url != urls[0]) {
            LogUtils.e("我更新了！！！")
            var i = 0
            while (i < urls.size) {
                noticesList.add(Notice(title[i], dates[i], urls[i]))
                i++
            }
        }
        return when (noticesList.size) {
            20 -> true
            else -> false
        }
    }

}